package cn.netty.example5;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;


public class EchoClientHandle extends ChannelHandlerAdapter {

    private final int number;
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        System.out.println("Server Response Message:"+msg+"");
    }


    public EchoClientHandle(int number){
        this.number= number;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {


        UserInfo[] userInfos = usersInfo();

        for (UserInfo userInfo: userInfos) {
            ctx.write(userInfo);
        }
        ctx.flush();

    }


    private UserInfo[] usersInfo(){


        UserInfo[] infos = new UserInfo[number];

        UserInfo userInfo = null;

        for (int i = 0; i < number; i++) {

            userInfo = new UserInfo();
            userInfo.setId(i);
            userInfo.setName("ABCDEF==>"+i);
            userInfo.setAge(i);
            infos[i] = userInfo;

        }


        return infos;
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("client is error :" + cause.getMessage());
        ctx.close();
    }
}
